package posts

import (
	"context"
	"fmt"
	"strings"

	"mall/common/modelx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/types/forum"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetPostsTagsListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetPostsTagsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPostsTagsListLogic {
	return &GetPostsTagsListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// #24.10.24#  首页标签
func (l *GetPostsTagsListLogic) GetPostsTagsList(in *forum.PostsTagsListReq) (*forum.PostsTagsListResp, error) {
	if in.Filter == nil || len(*in.Filter) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	preloadMap, eagerLoadMap := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)

	logrus.Info(fmt.Sprintf("GetPostsTagsList preloadMap: %+v", preloadMap))

	logrus.Info(fmt.Sprintf("GetPostsTagsList eagerLoadMap: %+v", eagerLoadMap))

	forumTermEntityName := model.RpcEntityNames.ForumTerm
	_, hasSettingMap := model.RpcEntityPreloadMap[forumTermEntityName]
	if !hasSettingMap {
		return &forum.PostsTagsListResp{}, nil
	}

	forumTermRepositoryName := model.RepositoryNames.ForumTerm
	columnMap, hasColumnMap := model.RepositoryPreloadMap[forumTermRepositoryName]
	if !hasColumnMap {
		return &forum.PostsTagsListResp{}, nil
	}

	var selectCols []string
	if preloadFields, hasPreloadFields := preloadMap[forumTermEntityName]; hasPreloadFields {
		selectCols = modelx.ParseSelectColumns(preloadFields, columnMap)
	}

	filterMap := modelx.ParseFilter(in.Filter, columnMap)
	logrus.Info(fmt.Sprintf("GetPostsTagsList filterMap: %+v", filterMap))
	if filterMap == nil {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	orderBy := modelx.ParseSorter(in.Sorter, columnMap)
	logrus.Info(fmt.Sprintf("GetPostsTagsList orderBy: %s", orderBy))
	if len(orderBy) == 0 {
		orderBy = model.ForumTermColumns.TermID + " DESC"
	}

	termList, _, err := l.svcCtx.ForumTerm.GetList(l.ctx, model.M{
		// "search":  in.Search,
		"select": strings.Join(selectCols, ","),
	}, -1, filterMap)
	if err != nil || len(termList) == 0 {
		return nil, err
	}
	var resp = &forum.PostsTagsListResp{}
	for _, v := range termList {
		resp.Tags = append(resp.Tags, &forum.PostsTags{
			Id:   pointy.GetPointer(v.TermID),
			Name: pointy.GetPointer(v.Name),
		})
	}

	return resp, nil
}
